package com.asia5b.a5mall.order.activity

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.config.CountrysRepository
import com.asia5b.a5mall.middleware.model.member.HouseModel
import com.asia5b.a5mall.middleware.model.bean.OrderListType
import com.asia5b.a5mall.middleware.model.bean.MenuBean
import com.asia5b.a5mall.middleware.base.BaseFragmentPagerAdapter
import com.asia5b.a5mall.middleware.utils.DisplayUtils
import com.asia5b.a5mall.middleware.utils.judge
import com.asia5b.a5mall.middleware.utils.sNewStanceFragment
import com.asia5b.a5mall.middleware.widget.GridSpacingItemDecoration
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.SelectAdapter
import com.asia5b.a5mall.order.databinding.ActivityOrderlistBinding
import com.asia5b.a5mall.order.fragment.OrderListFragment
import com.asia5b.a5mall.order.fragment.SearchOrderDF
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_orderlist.*

/**
 * Created by zhangyuncai on 2020/1/14.
 * 订单列表
 * 非自营:订单付款->wms仓库操作入库状态->订单状态(仓库已入库),在订单列表待发货可以看到这个订单->仓库操作发货->
 * ->wms仓库操作入库状态->订单状态(仓库已发货)->确认收货->确认收货成功后,在订单列表待评价可以看到这个订单->评价之后->
 * 这个订单过7天就到了已收货状态,在订单列表中已完成订单可以看到这个订单
 */
@Route(path = ActCons.OrderListActivity)
class OrderListActivity  : SimpleActivity<SimpleViewModel, ActivityOrderlistBinding>() {
    override val viewModelClazz: Class<SimpleViewModel>
        get() = SimpleViewModel::class.java

    override fun getDataBinding(): ActivityOrderlistBinding {
        initOrderListType = intent.getSerializableExtra("type") as OrderListType
        return ActivityOrderlistBinding.inflate(layoutInflater)
    }
    override var sIsDark = true
    val tab by lazy { tab_orderlist }
    val mViewPager by lazy { vp_orderlist }
    val fragments = arrayListOf<Fragment>()

    val typeList = arrayListOf<MenuBean>()

    val houseList = arrayListOf<HouseModel>()
    var currentHouse = -1

    var initOrderListType = OrderListType.ALL//刚进入界面时指定的订单类型

    var packageFragment: OrderListFragment? = null

    /**
     * 获取仓库或者订单类型
     */
    fun getPopupHouseAndOrderType(isHouse: Boolean = true): PopupWindow {
        val view = View.inflate(mActivity, R.layout.popup_ordertype_select, null)
        val popupWindow = PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true)
        val view_goodscomp_bg = view.findViewById<View>(R.id.view_ordertype_bg)
        view_goodscomp_bg.setOnClickListener {
            popupWindow.dismiss()
        }
        var mRecyclerView = view.findViewById<RecyclerView>(R.id.rv_orderlist_typelist)
        var tv_ordertype_title = view.findViewById<TextView>(R.id.tv_ordertype_title)

        //设置标题
        tv_ordertype_title.setText((isHouse).judge(R.string.所在仓库, R.string.订单类型))


        val mAdapter = SelectAdapter((isHouse).judge(houseList, typeList))
        if (isHouse) {
            mAdapter.selectPostion = currentHouse
        } else {
            mAdapter.selectPostion = mViewPager.currentItem
        }

        mRecyclerView.run {
            layoutManager = GridLayoutManager(context!!, 3)
            adapter = mAdapter
            if (itemDecorationCount == 0) {
                addItemDecoration(GridSpacingItemDecoration(3, DisplayUtils.dip2px(context!!, 10f), false))
            }
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (isHouse) {
                currentHouse = position
                packageFragment?.getDatas(1)
                setTitleView()
            } else {
                mViewPager.setCurrentItem(position, false)
            }
            popupWindow.dismiss()
        }

        return popupWindow
    }


    override fun initView() {
        initViewPager()
    }


    fun initViewPager() {
        val titles = arrayListOf<String>()
        fragments.clear()
        for (value in OrderListType.values()) {
            titles.add(getString(value.titleRes))
            var bundle = Bundle()
            bundle.putSerializable("type", value)
            val fragment = sNewStanceFragment(mActivity, OrderListFragment::class.java, bundle)
            if (value == OrderListType.APPLY_PACKAGING) {
                packageFragment = fragment
            }
            fragments.add(fragment)
            typeList.add(MenuBean(getString(value.titleRes)))
        }
        val pagerAdapter = BaseFragmentPagerAdapter(supportFragmentManager, fragments, titles)
        mViewPager.adapter = pagerAdapter
        tab.setupWithViewPager(mViewPager)
        mViewPager.offscreenPageLimit = fragments.size
        //切换到当前那一页
        mViewPager.setCurrentItem(initOrderListType.ordinal, false)
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(p0: Int) {
            }

            override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
            }

            override fun onPageSelected(p0: Int) {
                setTitleView()
            }

        })
        mViewPager.offscreenPageLimit = fragments.size


        setTitleView()
    }

    /**
     * 获取当前订单类型
     */
    fun getCurrentType(): OrderListType {
        for (value in OrderListType.values()) {
            if (value.ordinal == mViewPager.currentItem) {
                return value
            }
        }
        return OrderListType.ALL
    }

    fun setTitleView() {
        iv_orderlist_titlearrow.visibility = View.GONE
        var title = getString(R.string.我的订单)
        if (OrderListType.APPLY_PACKAGING.ordinal == mViewPager.currentItem) {
            val house_name = houseList.getOrNull(currentHouse)?.house_name ?: ""
            if (house_name.isNotEmpty()) {
                title = house_name
                iv_orderlist_titlearrow.visibility = View.VISIBLE
            }
        }
        tv_title_titletxt.text = title

        iv_orderlist_search.visibility = (getCurrentType() == OrderListType.WAIT_REFUND).judge(View.GONE, View.VISIBLE)
    }

    override fun initEvent() {
        typeEvent()
        houseEvent()

        iv_orderlist_search.setOnClickListener {
            SearchOrderDF().apply { currentOrderListType = getCurrentType() }.show(supportFragmentManager, localClassName)
        }
    }

    override fun initData() {
        getHouses()
    }

    fun getHouses() {
        CountrysRepository.anyOb<ArrayList<HouseModel>>(CountrysRepository.house)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    if (!it.isNullOrEmpty()) {
                        houseList.clear()
                        houseList.addAll(it)
                        currentHouse = 0
                        setTitleView()
                        packageFragment?.getDatas(1)
                    }
                }, Consumer {
                    it.printStackTrace()
                })
    }

    fun getCurrentHouseId(): Int? {
        if (houseList.isNullOrEmpty()) {
            getHouses()
        }
        return houseList.getOrNull(currentHouse)?.id
    }


    //todo 订单类型
    fun typeEvent() {
        iv_orderlist_typemenu.setOnClickListener {
            getPopupHouseAndOrderType(false).showAsDropDown(view_orderlist_divider)
        }
    }

    //todo 申请打包
    fun houseEvent() {
        //申请打包箭头
        ll_orderlist_titlearrow.setOnClickListener {
            if (OrderListType.APPLY_PACKAGING.ordinal == mViewPager.currentItem) {
                if (houseList.isNullOrEmpty()) {
                    getHouses()
                    return@setOnClickListener
                }
                getPopupHouseAndOrderType().showAsDropDown(view_orderlist_divider)
            }
        }
    }

    fun refreshOtherFragmentData() {
        for ((index, fragment) in fragments.withIndex()) {
            if (index != mViewPager.currentItem) {
                (fragment as OrderListFragment).hasFetchData = false
            }
        }
    }


}